package bourne.com.webservice.jaxws.handler;

import java.io.IOException;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

import org.springframework.stereotype.Component;

/**
 * Handler编写步骤 1)创建一个实现了SOAPHandler<SOAPMessageContext>的类
 * 2)在handleMessage()方法中编写代码 3)配置Handler,自定义一个名字随意的xml 4)在服务上启动过滤链
 * 在服务端或者客户端的Service实现类上使用@HandlerChain(file="myHandlerChain.xml")即可
 * 
 * @create May 17, 2013 12:07:54 AM
 * @author 玄玉<http://blog.csdn.net/jadyer>
 */
@Component
public class LogHandler implements SOAPHandler<SOAPMessageContext> {
	@Override
	public Set<QName> getHeaders() {
		return null;
	}

	@Override
	public void close(MessageContext context) {

	}

	@Override
	public boolean handleFault(SOAPMessageContext context) {
		System.out.println("Server.handleFault() is invoked......");
		return false;
	}

	@Override
	@SuppressWarnings("unchecked")
	public boolean handleMessage(SOAPMessageContext context) {
		System.out.println("Server.handleMessage() is invoked......");
		// 只有Handler被纳入Spring管理后,这里获取到的HttpServletRequest才不是null
		HttpServletRequest request = (HttpServletRequest) context.get(SOAPMessageContext.SERVLET_REQUEST);
		System.out.println("RealPath=" + request.getSession().getServletContext().getRealPath("/"));

		// 从服务端角度看:inbound表示接收客户端消息,outbound表示响应消息给客户端..从客户端角度看时正好与之相反
		Boolean isOutBound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
		if (isOutBound) {
			System.out.println("输出消息：");
		} else {
			System.out.println("请求的服务是:" + context.get("javax.xml.ws.wsdl.interface"));
			System.out.println("请求的服务IMPL是:" + context.get("javax.xml.ws.wsdl.interface"));
			System.out.print("输入消息");
		}

		SOAPMessage message = context.getMessage();
		try {
			SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();

			message.writeTo(System.out);
			System.out.println();
			System.out.println("消息结束");
		} catch (SOAPException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return true;
	}
}